package code;

import code.Product;
import java.io.*;
import java.util.*;

public class ProductService {
    private final Map<String, Product> productData = new HashMap<>();
    private String dataFilePath; // 数据文件路径（从配置文件读取）

    public ProductService() {
        loadConfig();
        loadData();
        if (productData.isEmpty()) {
            initDefaultProducts();
        }
    }

    // 初始化默认商品（数据文件不存在时调用）
    private void initDefaultProducts() {
        Set<String> programTags = new HashSet<>();
        programTags.add("编程");
        programTags.add("畅销");
        productData.put("p001", new Product("p001", "Java从入门到精通", 99.0, 100, programTags));

        productData.put("p002", new Product("p002", "高性能MySQL", 128.5, 50));

        Set<String> healthTags = new HashSet<>();
        healthTags.add("健康");
        healthTags.add("实用");
        healthTags.add("热门");
        productData.put("p003", new Product("p003", "颈椎康复指南", 45.0, 200, healthTags));

        productData.put("p004", new Product("p004", "生发秘籍", 88.0, 0));
        productData.put("p005", new Product("p005", "无线蓝牙鼠标", 129.0, 80));
        productData.put("p006", new Product("p006", "机械青轴键盘", 299.0, 30));
    }

    // 加载配置文件
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStreamReader isr = new InputStreamReader(
                new FileInputStream("config.properties"), "UTF-8")) {
            props.load(isr);
            dataFilePath = props.getProperty("data.file.path", "products.dat");
        } catch (FileNotFoundException e) {
            System.out.println("配置文件不存在，使用默认路径: products.dat");
            dataFilePath = "products.dat";
        } catch (IOException e) {
            System.out.println("加载配置失败: " + e.getMessage());
            dataFilePath = "products.dat";
        }
    }

    // 保存商品数据到文件
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(dataFilePath))) {
            oos.writeObject(productData);
            System.out.println("数据已保存到: " + dataFilePath);
        } catch (IOException e) {
            System.out.println("保存数据失败: " + e.getMessage());
        }
    }

    // 从文件加载商品数据
    @SuppressWarnings("unchecked")
    private void loadData() {
        File dataFile = new File(dataFilePath);
        if (!dataFile.exists()) {
            System.out.println("数据文件不存在，将使用默认商品数据");
            return;
        }
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(dataFilePath))) {
            productData.clear();
            productData.putAll((Map<String, Product>) ois.readObject());
            System.out.println("已从 " + dataFilePath + " 加载商品数据");
        } catch (FileNotFoundException e) {
            System.out.println("数据文件不存在");
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("加载数据失败: " + e.getMessage());
        }
    }

    public List<Product> getAllProducts() {
        return new ArrayList<>(productData.values());
    }

    public Product findProductById(String id) {
        return productData.get(id);
    }

    public String getDataFilePath() {
        return dataFilePath;
    }
}